package com.ruoyi.ejkgl.ejkck.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import com.ruoyi.ejkgl.ejkck.domain.Ejkck;
import com.ruoyi.ejkgl.ejkck.domain.EjkckCkmx;
import com.ruoyi.ejkgl.ejkck.service.IEjkckService;
import com.ruoyi.ejkgl.ejkwz.domain.Ejkwz;
import com.ruoyi.ejkgl.ejkwz.service.IEjkwzService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

/**
 * 二级库出库Controller
 *
 * @author huacai
 * @date 2024-12-11
 */
@RestController
@RequestMapping("/ejkgl/ejkck")
public class EjkckController extends BaseController {
    @Resource
    private IEjkckService ejkckService;

    @Resource
    private IEjkwzService ejkwzService;

    /**
     * 查询二级库出库列表
     */
    @GetMapping("/list")
    public TableDataInfo list(Ejkck ejkck) {
        startPage();
        List<Ejkck> list = ejkckService.selectEjkckList(ejkck);
        return getDataTable(list);
    }

    /**
     * 导出二级库出库列表
     */
    @Log(title = "二级库出库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Ejkck ejkck) {
        List<Ejkck> list = ejkckService.selectEjkckList(ejkck);
        ExcelUtil<Ejkck> util = new ExcelUtil<Ejkck>(Ejkck.class);
        util.exportExcel(response, list, "二级库出库数据");
    }

    /**
     * 下载模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<Ejkck> util = new ExcelUtil<Ejkck>(Ejkck.class);
        util.importTemplateExcel(response, "二级库出库数据");
    }

    /**
     * 导入数据
     */
    @Log(title = "二级库出库", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file) throws Exception {
        ExcelUtil<Ejkck> util = new ExcelUtil<Ejkck>(Ejkck.class);
        InputStream inputStream = file.getInputStream();
        List<Ejkck> list = util.importExcel(inputStream);
        inputStream.close();
        int count = ejkckService.batchInsertEjkck(list);
        return AjaxResult.success("导入成功" + count + "条信息！");
    }

    /**
     * 获取二级库出库详细信息
     */
    @GetMapping(value = "/{ejkckId}")
    public AjaxResult getInfo(@PathVariable("ejkckId") String ejkckId) {
        return success(ejkckService.selectEjkckByEjkckId(ejkckId));
    }

    /**
     * 新增二级库出库
     */
    @Log(title = "二级库出库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Ejkck ejkck) {
        return toAjax(ejkckService.insertEjkck(ejkck));
    }

    /**
     * 修改二级库出库
     */
    @Log(title = "二级库出库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Ejkck ejkck) {
        return toAjax(ejkckService.updateEjkck(ejkck));
    }

    /**
     * 删除二级库出库
     */
    @Log(title = "二级库出库", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ejkckIds}")
    public AjaxResult remove(@PathVariable String[] ejkckIds) {
        return toAjax(ejkckService.deleteEjkckByEjkckIds(ejkckIds));
    }

    /**
     * 获得二级库出库主键ID (UUID)
     */
    @GetMapping("/getEjkCkId")
    public AjaxResult getEjkCkId() {
        String getEjkCkId = IdUtils.fastSimpleUUID();
        return success(getEjkCkId);
    }

    /**
     * 确定出库
     */
    @Log(title = "确定出库", businessType = BusinessType.UPDATE)
    @PutMapping("/updateQdCk")
    public AjaxResult updateQdDb(@RequestBody Ejkck ejkck) {
        ejkck.setCkZt("出库完成");

        //获取二级库出库明细List
        List<EjkckCkmx> ejkckCkmxList = ejkck.getEjkckCkmxList();
        // 预检查阶段
        for (EjkckCkmx ejkckCkmx : ejkckCkmxList) {
            String ejkwzId = ejkckCkmx.getEjkwzId(); // 二级库物资ID
            Integer ckSl = ejkckCkmx.getCkSl(); // 出库数量

            // 根据 二级库物资ID 查询二级库物资
            Ejkwz ejkwzById = ejkwzService.selectEjkwzByEjkwzId(ejkwzId);
            Integer kc = ejkwzById.getKc(); // 该物资出库前的库存

            if (kc < ckSl) { // 如果库存 小于 出库数量
                return AjaxResult.error("出库单中:" + ejkckCkmx.getWzName() + " 库存小于出库数量, 请检查!");
            }
        }

        // 如果预检查通过，执行更新阶段
        for (EjkckCkmx ejkckCkmx : ejkckCkmxList) {
            String ejkwzId = ejkckCkmx.getEjkwzId(); // 二级库物资ID
            Integer ckSl = ejkckCkmx.getCkSl(); // 出库数量

            // 再次查询以确保数据一致性（考虑到可能有并发操作）
            Ejkwz ejkwzById = ejkwzService.selectEjkwzByEjkwzId(ejkwzId);
            Integer kc = ejkwzById.getKc(); // 该物资出库前的库存

            // 构建新的二级库物资实体类
            Ejkwz ejkwz = new Ejkwz();
            ejkwz.setEjkwzId(ejkwzId); // 二级库物资ID
            ejkwz.setKc(kc - ckSl); // 本身库存 - 出库数量
            ejkwzService.updateEjkwz(ejkwz); // 调用二级库物资的修改方法
        }


        return toAjax(ejkckService.updateEjkck(ejkck));
    }

}
